package com.cjm.algorithm.leetcode;

import com.cjm.algorithm.TreeNode;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import java.util.concurrent.LinkedBlockingQueue;

public class RnvertTree226 {
    public static TreeNode invertTree(TreeNode root) {
        Queue<TreeNode> queue = new LinkedBlockingQueue<>();
        if (root == null) queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node == null) continue;
                TreeNode left = node.left;
                TreeNode right = node.right;
                node.left = right;
                node.right = left;
                if (left != null) queue.add(left);
                if (right != null) queue.add(right);
            }
        }
        return root;
    }

    private static TreeNode m2(TreeNode root) {
        if (root == null) return null;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node == null) continue;
            TreeNode left = node.left;
            TreeNode right = node.right;
            node.left = right;
            node.right = left;
            stack.push(left);
            stack.push(right);
        }
        return root;
    }

    private static TreeNode m1(TreeNode root) {
        if (root == null) {
            return null;
        }
        invertTree(root.left);
        invertTree(root.right);
        TreeNode left = root.left;
        TreeNode right = root.right;
        root.left = right;
        root.right = left;
        return root;
    }

    public static void main(String[] args) {
        TreeNode treeNode = TreeNode.generatorTreeNode(new Integer[]{4,2,7,1,3,6,9});
        TreeNode x = invertTree(treeNode);
        System.err.println(x);
    }
}
